package com.buildings.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.buildings.R;
import com.buildings.api.Api;
import com.buildings.base.BaseActivity;
import com.buildings.bean.FormListBean;
import com.buildings.bean.FormListResultBean;
import com.buildings.http.BaseCallBack;
import com.buildings.http.MyHttpClient;
import com.buildings.permissions.Acp;
import com.buildings.permissions.AcpListener;
import com.buildings.permissions.AcpOptions;
import com.buildings.util.CustomToast;
import com.buildings.util.DialogUtils;
import com.buildings.util.GPSUtil;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

public class TaskMapActivity extends BaseActivity implements View.OnClickListener {

    public static final String FROM_TASK_MAP = "FROM_TASK_MAP";

    private WebView webView;
    private String mapInfo;//地图范围面积 // 95.72929,39.82741;98.80546,39.42123;97.0916,38.53302;
    private String taskId;
    private String taskName;
    private String status;

    private int pageNum = 1;//当前请求页数
    private int pageSize = 100000;
    private Dialog dialog;

    private List<FormListBean.FormBean> result ;

    private Timer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        askMultiPermission();
    }

    public void initView(){
        mapInfo = getIntent().getStringExtra("mapInfo");
        taskId = getIntent().getStringExtra("taskId");
        taskName = getIntent().getStringExtra("taskName");
        status = getIntent().getStringExtra("status");
        TextView title = findViewById(R.id.tv_title);
        title.setText("选择建筑物");
        findViewById(R.id.iv_back).setOnClickListener(this);
        webView = findViewById(R.id.webview);
        webView.setHorizontalScrollBarEnabled(false);//水平不显示
        webView.setVerticalScrollBarEnabled(false); //垂直不显示
        WebSettings webSettings = webView.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setJavaScriptEnabled(true);//启用js
        webSettings.setBlockNetworkImage(false);//解决图片不显示
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setGeolocationDatabasePath( getFilesDir().getPath() );
        webSettings.setDatabaseEnabled(true);//
        webSettings.setGeolocationEnabled(true);//
        webView.addJavascriptInterface(new MyJavaInterface(),"androidObject");
//支持缩放，默认为true。
        webSettings.setSupportZoom(false);
//        webSettings.setBuiltInZoomControls(true);
//调整图片至适合webview的大小
        webSettings.setUseWideViewPort(false);
// 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(false);
//设置默认编码
        webSettings.setDefaultTextEncodingName("utf-8");
////设置自动加载图片
        webSettings.setLoadsImagesAutomatically(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError errorResponse) {
                super.onReceivedError(view, request, errorResponse);
            }
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                //6.0以下执行
                //网络未连接
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //116.2788,40.14234   116.28189,40.14357  116.27973,40.14009  116.28284,40.14071
               if(!TextUtils.isEmpty(mapInfo)){
                   String[] array = mapInfo.split(";");
                   if(!TextUtils.isEmpty(array[0])){
                       String[] lnglat = array[0].split(",");
                       String centerParams = "'"+lnglat[0]+"','"+lnglat[1]+"'";
                       webView.loadUrl("javascript:centerAndZoom("+centerParams+")");
                   }
                   String params = "'"+mapInfo+"'";
                   //String params = "'116.2788','40.14234','116.28189','40.14357','116.28284','40.14071','116.27973','40.14009'";
                   webView.loadUrl("javascript:onRange("+params+")");
               }
                //开始调用获取表单列表接口
                dialog = DialogUtils.showRefreshDialog(activity);
                //4 表示全部
                getFormList(taskId,"4","4");

            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

        });
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }
        });
        webView.loadUrl("file:///android_asset/map.html");
//        webView.loadUrl("file:///android_asset/images/map.html");

        //实时定位
        startLocation();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private void startLocation(){

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadUrl("javascript:setPhoneLocation()");
                       // Log.e("startLocation","timer------");
                    }
                });
            }
        },1000,5000);

    }

    private void startForm(FormListBean.FormBean bean){
        //0、城镇住宅1、城镇非住宅，2、农村住房，3、农村公共住宅
        Intent intent = null;
        if(TextUtils.equals(bean.getBulidingType(),"0")){
            intent = new Intent(activity,TownHouseFormActivity.class);

        }else if(TextUtils.equals(bean.getBulidingType(),"1")){
            intent = new Intent(activity,TownNonHouseFormActivity.class);

        }else if(TextUtils.equals(bean.getBulidingType(),"2")){
            intent = new Intent(activity,VillageHouseFormActivity.class);

        }else {
            intent = new Intent(activity,VillagePublicFormActivity.class);

        }
        String type = bean.getSpType();//表单状态  0未提交  1未审核  2审核未通过 3审核通过
        if(TextUtils.equals("0",type) || TextUtils.equals("2",type)){
            //未提交  审核未通过   可以编辑
            intent.putExtra("isEdit",true);
        }else {
            //不可以编辑，只能查看
            intent.putExtra("isEdit",false);
        }
        if(TextUtils.equals("2",status)){
            //任务已完成，表单都不可编辑
            intent.putExtra("isEdit",false);
        }
        intent.putExtra("isFirst",false);
        intent.putExtra("formId",bean.getFormId());
        intent.putExtra("taskName",taskName);
        intent.putExtra("taskId",taskId);
        intent.putExtra("buildType",bean.getBulidingType());
        intent.putExtra("lng",bean.getBulidingLongitude());
        intent.putExtra("lat",bean.getBulidingLatitude());
        intent.putExtra("from",FROM_TASK_MAP);
        startActivityForResult(intent,1000);
    }


    public class MyJavaInterface {


        @JavascriptInterface
        public void androidMarkerClick( String lng,  String lat ){
            Log.e("androidMarkerClick经纬度",lng+","+lat);
            //点击标注
            if(result != null){
                for(FormListBean.FormBean bean : result){
                    //遍历集合，查找经纬度相同的对象，就是所点击的表单建筑
                    if(TextUtils.equals(lng,bean.getBulidingLongitude()) && TextUtils.equals(lat,bean.getBulidingLatitude())){
                        //跳转到表单详情，判断是否可以编辑
                        startForm(bean);
                        return;
                    }
                }
            }
        }

        @JavascriptInterface
        public void androidMapClick( String lng,  String lat ){
            Log.e("点击的经纬度",lng+","+lat);
            androidMapClick(lng,lat,"","");

        }

        @JavascriptInterface
        public void androidMapClick(final String lng, final String lat,final String locationLng,final String locationLat){
            //横竖屏切换  0竖屏   1横屏 somehowTheScreen
            Log.e("经纬度",lng+","+lat);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(!TextUtils.equals(status,"2")){
//dialog选择建筑类型
                        DialogUtils.showBuildSelectDialog(activity, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                int type = (int) v.getTag();
                                Intent intent = null;
                                String iconUrl = "";
                                switch (type){
                                    case 1:
                                        //城镇住宅
                                        iconUrl = "images/ic_town_house.png";
                                        intent = new Intent(activity,TownHouseFormActivity.class);
                                        break;
                                    case 2:
                                        //城镇非住宅
                                        iconUrl = "images/ic_town_no_house.png";
                                        intent = new Intent(activity,TownNonHouseFormActivity.class);
                                        break;
                                    case 3:
                                        //农村住宅
                                        iconUrl = "images/ic_village_house.png";
                                        intent = new Intent(activity,VillageHouseFormActivity.class);
                                        break;
                                    case 4:
                                        //农村公共建筑
                                        iconUrl = "images/ic_village_public_build.png";
                                        intent = new Intent(activity,VillagePublicFormActivity.class);
                                        break;
                                }

                                intent.putExtra("isFirst",true);
                                intent.putExtra("lng",lng);
                                intent.putExtra("lat",lat);
                                intent.putExtra("taskId",taskId);
                                intent.putExtra("taskName",taskName);
                                intent.putExtra("locationLng",locationLng);
                                intent.putExtra("locationLat",locationLat);
                                intent.putExtra("from",FROM_TASK_MAP);
                                startActivityForResult(intent,1000);
                                //此处请求接口，新的表单

                                //在地图标记对应建筑116.288  40.1543
//                            webView.loadUrl("javascript:addIconMarker('"+lng+"','"+lat+"','"+iconUrl+"')");
//                            webView.loadUrl("javascript:addIconMarker('116.288','40.1543','http://api.tianditu.gov.cn/img/map/markerA.png')");
                            }
                        },true);
                    }

                }
            });

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1000 && resultCode == RESULT_OK){
            if(dialog != null){
                dialog.show();
            }
            webView.loadUrl("javascript:centerAndZoom('1','1')");
            getFormList(taskId,"4","4");
        }
    }

    private void getFormList(String taskId, String type, String buildType) {
        String url = Api.FORM_LIST+"?taskId="+taskId+"&type="+type+"&buildType="+buildType+"&curtPage="+pageNum+"&pageSize="+pageSize;

        MyHttpClient
                .newBuilder()
                .get()
                .url(url)
//                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<FormListResultBean>() {
                    @Override
                    public void onSuccess(FormListResultBean bean) {
                        super.onSuccess(bean);
                        if(bean.getCode() == 200 && bean.getData() != null){
                            result = bean.getData().getRows();
                            for(FormListBean.FormBean formBean : result){
                                //往地图上添加对应的表单
//                                webView.loadUrl("javascript:addMarker('"+formBean.getBulidingLongitude()
//                                        +"','"+formBean.getBulidingLatitude()+"')");
                                String lng = formBean.getBulidingLongitude();
                                String lat = formBean.getBulidingLatitude();
                                String buildType = formBean.getBulidingType();
                                String iconUrl = "";
                                //0、城镇住宅1、城镇非住宅，2、农村住房，3、农村公共住宅
                                if(TextUtils.equals("0",buildType)){
                                    //城镇住宅 "images/ic_village_public_build.png";
                                    if(TextUtils.equals("0",formBean.getSpType())){ //表单状态  0未提交  1未审核  2审核未通过 3审核通过
                                       //未提交
                                        iconUrl = "images/town_house_no_commit.png";
                                    }else if(TextUtils.equals("1",formBean.getSpType())){
                                        //未审核
                                        iconUrl = "images/town_house_no_verify.png";
                                    }if(TextUtils.equals("2",formBean.getSpType())){
                                        //审核未通过
                                        iconUrl = "images/town_house_verify_failed.png";
                                    }if(TextUtils.equals("3",formBean.getSpType())){
                                        //审核成功
                                        iconUrl = "images/town_house_verify_success.png";
                                    }
                                }else if(TextUtils.equals("1",buildType)){
                                    //城镇非住宅
                                    if(TextUtils.equals("0",formBean.getSpType())){ //表单状态  0未提交  1未审核  2审核未通过 3审核通过
                                        //未提交
                                        iconUrl = "images/town_nonhouse_no_commit.png";
                                    }else if(TextUtils.equals("1",formBean.getSpType())){
                                        //未审核
                                        iconUrl = "images/town_nonhouse_no_verify.png";
                                    }if(TextUtils.equals("2",formBean.getSpType())){
                                        //审核未通过
                                        iconUrl = "images/town_nonhouse_verify_failed.png";
                                    }if(TextUtils.equals("3",formBean.getSpType())){
                                        //审核成功
                                        iconUrl = "images/town_nonhouse_verify_success.png";
                                    }
                                }else if(TextUtils.equals("2",buildType)){
                                    //农村住房
                                    if(TextUtils.equals("0",formBean.getSpType())){ //表单状态  0未提交  1未审核  2审核未通过 3审核通过
                                        //未提交
                                        iconUrl = "images/village_house_no_commit.png";
                                    }else if(TextUtils.equals("1",formBean.getSpType())){
                                        //未审核
                                        iconUrl = "images/village_house_no_verify.png";
                                    }if(TextUtils.equals("2",formBean.getSpType())){
                                        //审核未通过
                                        iconUrl = "images/village_house_verify_failed.png";
                                    }if(TextUtils.equals("3",formBean.getSpType())){
                                        //审核成功
                                        iconUrl = "images/village_house_verify_success.png";
                                    }
                                }else if(TextUtils.equals("3",buildType)){
                                    //农村公共住宅
                                    if(TextUtils.equals("0",formBean.getSpType())){ //表单状态  0未提交  1未审核  2审核未通过 3审核通过
                                        //未提交
                                        iconUrl = "images/village_public_no_commit.png";
                                    }else if(TextUtils.equals("1",formBean.getSpType())){
                                        //未审核
                                        iconUrl = "images/village_public_no_verify.png";
                                    }if(TextUtils.equals("2",formBean.getSpType())){
                                        //审核未通过
                                        iconUrl = "images/village_public_verify_failed.png";
                                    }if(TextUtils.equals("3",formBean.getSpType())){
                                        //审核成功
                                        iconUrl = "images/village_public_verify_success.png";
                                    }
                                }
//                                iconUrl = "images/ic_town_no_house.png";
                                webView.loadUrl("javascript:addIconMarker('"+lng+"','"+lat+"','"+iconUrl+"')");

                            }


                        }else {
                            CustomToast.showToast(activity,"获取建筑信息失败");
                        }
                        if (dialog != null)
                            dialog.dismiss();
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        CustomToast.showToast(activity,"网络异常");
                        if (dialog != null)
                            dialog.dismiss();
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        CustomToast.showToast(activity,"网络异常");
                        if (dialog != null)
                            dialog.dismiss();
                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer != null){
            timer.cancel();
        }
    }

    private AMapLocationClient mlocationClient;
    /**
     * 高德定位
     */
    private void geocodeLocation(){
        //声明mlocationClient对象
        //声明mLocationOption对象
        Log.e("geocodeLocation","开始定位");
        AMapLocationClientOption mLocationOption = null;
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                Log.e("TAG","定位结果"+aMapLocation.getErrorCode());
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //定位成功回调信息，设置相关消息
                        aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                        double latitude = aMapLocation.getLatitude();//获取纬度
                        double longitude = aMapLocation.getLongitude();//获取经度
                        double[] a = GPSUtil.gcj02_To_Gps84(latitude,longitude);
//        double[] a =  GPSUtil.gps84_To_Gcj02(39.92361,116.38094);
                        Log.e("lat","lat=" +a[0]);
                        Log.e("lon","lon=" +a[1]);
                        aMapLocation.getAccuracy();//获取精度信息
                        String province = aMapLocation.getProvince();
                        String city = aMapLocation.getCity();
                        String district = aMapLocation.getDistrict();
                        String street = aMapLocation.getStreet();
                        String detail = aMapLocation.getDescription();
//                        String message = "javascript:"+Constant.JS_FUNC_GEOGRAPHICAL_LOCATION+"('"+longitude+"','"+latitude+"','"+aMapLocation.getCity()+"')";
                        Log.e("TAG","定位 = province="+province+" city="+city+" district="+district+" street = "+street+" detail= "+detail);
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date(aMapLocation.getTime());
                        df.format(date);//定位时间
//                        webView.loadUrl("javascript:addMarker("+a[1]+","+a[0]+")");
                        Message message = Message.obtain();
                        message.obj = a;
                        handler.sendMessageDelayed(message,5000);
                        mlocationClient.stopLocation();
                        return;
                    } else {
                        //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
//                        Log.e("AmapError","location Error, ErrCode:"
//                                + aMapLocation.getErrorCode() + ", errInfo:"
//                                + aMapLocation.getErrorInfo());
                    }
                }

            }
        });
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();

    }

    private void askMultiPermission() {
        Acp.getInstance(this).
                request(new AcpOptions.Builder()
                                .setPermissions(
//                                        Manifest.permission.CAMERA,
                                        Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                        //                               Manifest.permission.RECEIVE_SMS,
                                        Manifest.permission.ACCESS_FINE_LOCATION,
                                        Manifest.permission.ACCESS_COARSE_LOCATION
//                                        Manifest.permission.RECORD_AUDIO
                                )

                                /*以下为自定义提示语、按钮文字
                                .setDeniedMessage()
                                .setDeniedCloseBtn()
                                .setDeniedSettingBtn()
                                .setRationalMessage()
                                .setRationalBtn()*/

                                .build(),
                        new AcpListener() {
                            @Override
                            public void onGranted() {
                                initView();
//                                geocodeLocation();
                            }

                            @Override
                            public void onDenied(List<String> permissions) {

                            }
                        });
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            double[] a = (double[]) msg.obj;
//            webView.loadUrl("javascript:addMarker("+a[1]+","+a[0]+")");
        }
    };

}
